<script setup lang="ts">
import { reactive, computed, ref, toRefs, onMounted, watch } from "vue";
import { ContentWrap } from "@/components/ContentWrap";
import { ElInput, ElMessage } from "element-plus";
import type { ElForm } from "element-plus";
import { Edit, Plus, Minus } from "@element-plus/icons-vue";
import { BaseButton } from "@/components/Button";
import { useRouter, useRoute } from "vue-router";
import {
  airportAdd,
  airportEdit,
  airportFindDeail,
  getDroneList,
} from "@/api/resource-manage";
import {
  baseOpions,
  setpOpions,
  getType,
  otherOpions,
  getMountType,
  getSeriesType,
  setDroneType,
  queryDroneList,
} from "./config/info";
import { dataToSelect } from "@/utils";

// 路由
const router = useRouter();
const { query } = useRoute();

// 基础信息ref
const elFormRef = ref<ComponentRef<typeof ElForm>>();
const mountRef = ref<ComponentRef<typeof ElForm>>();
const formSize = ref("default");

// 接口数据详情
let apiObj = ref<T>({});


// add 新增  eidt 编辑   detail 详情
let infoType = computed(() => {
  return query?.type ?? "add";
});

// 基础信息
const formObj = computed(() => {
  return {
    ...baseOpions,
  };
});

// 表单参数
const modalForm = computed(() => {
  if (infoType.value !== "add") {
    return reactive({
      code: apiObj.value.code, // 机库编号
      brand: apiObj.value.code, // 机库品牌
      modelCode: apiObj.value.code, // 机库型号
      status: apiObj.value.code, // 机库状态(1可用 0不可用 2报废)
      onLineStatus: apiObj.value.onLineStatus, // 1在线 0不在线
      name: apiObj.value.code, // 机库名称
      coord: apiObj.value.coord, // 坐标
      longitude: null, // 经度
      latitude: null, // 纬度
      pointCoord: apiObj.value.pointCoord, // 备降坐标
      pointLongitude: null, // 备降点经度
      pointLatitude: null, // 备降点纬度
      internalMonitorUrl: apiObj.value.internalMonitorUrl, // 内部监控地址
      externalMonitorUrl: apiObj.value.externalMonitorUrl, // 外部监控地址
      id: apiObj.value.id,
    });
  } else {
    return reactive({
      ...formObj.value.modalForm,
    });
  }
});

// 操作记录
const setpsShow = ref(true);
// 管理无人机
const setpActive = ref(0);

// 管理无人机
const mountForm = computed(() => {
  return {
    ...otherOpions,
  };
});

// 管理无人机 表单参数
const mountModalForm = computed(() => {
  if (infoType.value !== "add") {
    return reactive({
      droneBrand: apiObj.value.droneBrand,
      droneCode: apiObj.value.droneCode,
      droneId: apiObj.value.droneId,
    });
  } else {
    return reactive({
      ...mountForm.value.modalForm,
    });
  }
});

// 查询无人机列表
watch(
  [() => mountModalForm.value.droneBrand, () => mountModalForm.value.droneCode],
  ([newDroneBrand, newDroneCode], [oldDroneBrand, oldDroneCode]) => {
    console.log(newDroneBrand, newDroneCode, oldDroneBrand, oldDroneCode);
    if (newDroneBrand && newDroneCode) {
      queryDroneList(newDroneBrand, newDroneCode);
    }
  }
);

// 操作记录
const setps = computed(() => {
  return {
    ...setpOpions,
  };
});

// 确认
const submit = async (formEl, formMount) => {
  if (!formEl) return;
  let elForm = await formEl.validate();
  let elMount = await formMount.validate();
  if (!!elForm) {
    let coord = modalForm.value.coord || null;
    let pointCoord = modalForm.value.pointCoord || null;
    let query = {
      ...modalForm.value,
      longitude: coord?.split(",")[0] || "", // 经度
      latitude: coord?.split(",")[1] || "", // 纬度
      pointLongitude: pointCoord?.split(",")[0] || "", // 备降点经度
      pointLatitude: pointCoord?.split(",")[1] || "", // 备降点纬度
      droneId: mountModalForm.value.droneId,
    };
    //新增
    if (infoType.value === "add") {
      const { msg } = (await airportAdd(query)) as any;
      ElMessage.success(msg);
    } else {
      // 编辑
      const { msg } = (await airportEdit(query)) as any;
      ElMessage.success(msg);
    }
    returnLinK();
  } else {
    console.log("error submit!");
  }
};

// 返回
const returnLinK = () => {
  router.go(-1);
};

// 载入
onMounted(() => {
  init();
});

// 载入
const init = () => {
  getType();
  setDroneType();
  if (infoType.value !== "add") {
    getDeail(query?.id);
  }
};



// 获取详情
const getDeail = async function (airportId) {
  const { data } = (await airportFindDeail({ airportId })) as any;
  const coord = (data.longitude = "," + data.longitude);
  const pointCoord = data.pointLongitude + "," + data.pointLatitude;
  apiObj.value = {
    ...data,
    coord,
    pointCoord,
    droneBrand: data.drone?.brand,
    droneCode: data.drone?.modelCode,
    droneId: data.drone?.code
  };
};
</script>

<template>
  <!--  基础信息 -->
  <ContentWrap :title="`基础信息`" style="margin-bottom: 20px">
    <el-form
      ref="elFormRef"
      :model="modalForm"
      :rules="formObj.modalRules"
      label-width="120px"
      :size="formSize"
      status-icon
      :disabled="infoType === 'detail'"
    >
      <el-row :gutter="10">
        <el-col
          v-for="(formItem, index) in formObj.formItem"
          :key="index"
          v-bind="formItem.row"
        >
          <el-form-item :label="formItem.label" :prop="formItem.key">
            <el-input
              v-if="formItem.type === 'input'"
              v-model="modalForm[formItem.key]"
              v-bind="formItem.props"
            >
              <template v-if="formItem.key === 'coverage'" #append>km</template>
            </el-input>
            <el-select
              v-if="formItem.type === 'select'"
              v-model="modalForm[formItem.key]"
              v-bind="formItem.props"
            >
              <el-option
                v-for="item in formItem.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>
  <!-- 管理无人机 -->
  <ContentWrap :title="`管理无人机`" style="margin-bottom: 20px">
    <el-form
      ref="mountRef"
      :model="mountModalForm"
      label-width="120px"
      :size="formSize"
      :disabled="infoType === 'detail'"
      status-icon
    >
      <el-row :gutter="10">
        <el-col
          v-bind="formItem.row"
          v-for="(formItem, index) in mountForm.formItem"
          :key="index"
        >
          <el-form-item
            :label="formItem.label"
            :prop="formItem.key"
            :rules="formItem.rules"
          >
            <el-select v-model="mountModalForm[formItem.key]" v-bind="formItem.props">
              <el-option
                v-for="item in formItem.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>
  <!-- 操作记录 -->
  <ContentWrap :title="`操作记录`" style="margin-bottom: 20px">
    <el-steps :active="setpActive" align-center>
      <el-step
        v-for="(item, index) in setps"
        :key="index"
        :title="item.title"
        :description="item.description"
      >
      <template #icon>
          <span :class="item.icon" class="icon_span"></span>
        </template>
      </el-step>
    </el-steps>
  </ContentWrap>
  <el-row>
    <el-col :span="24">
      <BaseButton @click="returnLinK()">返回</BaseButton>
      <BaseButton
        v-if="infoType !== 'detail'"
        type="primary"
        @click="submit(elFormRef, mountRef)"
        >确认</BaseButton
      >
    </el-col>
  </el-row>
</template>

<style lang="less" scoped>
.el-form-item__content {
  > div {
    width: 100%;
  }
}

.mount-group {
  display: flex;
  .group {
    flex: 1;
  }
  .handle-warp {
    width: 110px;
    margin-left: 15px;
  }
}
</style>
